using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MeetingRoom.Domain;
using MeetingRoom.Support;
using MeetingRoom.Service;
using MeetingRoom.Service.Workflow;
using MeetingRoom.Data;

namespace MeetingRoom.Service.Workflow.Implementation
{
    /// <summary>
    /// Summary description for AvailablityCheckingPhase
    /// </summary>
    public class AvailablityCheckingPhase : IWorkflowPhase
    {
        protected IGetMeetingRoomTypes getMeetingRoomTypesImplementor = null;

        protected IGetSchedulesByMeetingRoomType queryImplementor = null;

        public AvailablityCheckingPhase()
        {

        }

        public IGetMeetingRoomTypes GetMeetingRoomTypeImplementor
        {
            set
            {
                this.getMeetingRoomTypesImplementor = value;
            }
        }

        public IGetSchedulesByMeetingRoomType GetSchedulesByMeetingRoomTypeImplementor
        {
            set
            {
                this.queryImplementor = value;
            }
        }

        #region IWorkflowPhase Members

        public void Execute(object request)
        {
            Assert.IsNotNull(request, "Request");
            Assert.IsNotNull(this.queryImplementor, "Query Implementor is not yet assigned.");

            int conflictedCount = 0;
            Schedule schedule = (Schedule)request;

            MeetingRoomType[] meetingRoomTypes = 
                this.getMeetingRoomTypesImplementor.GetMeetingRoomTypes(
                schedule.MeetingRoomType);

            foreach (MeetingRoomType meetingRoomType in meetingRoomTypes)
            {
                List<Schedule> schedules 
                    = queryImplementor.GetSchedulesByMeetingRoomType(meetingRoomType);

                foreach (Schedule registeredSchedule in schedules)
                {
                    if (registeredSchedule.Duration.Intersect(schedule.Duration))
                    {
                        conflictedCount++;
                    }
                }

                if (conflictedCount < meetingRoomType.Count)
                {
                    Console.WriteLine(string.Format("conflected: {0}", conflictedCount));
                    return;
                }
            }

            throw new MeetingRoomUnavaliableException();
        }

        #endregion
    }
}